package com.lorenzogao.jetpackexample.datastore

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey

import androidx.datastore.preferences.core.stringPreferencesKey

import androidx.datastore.preferences.preferencesDataStore
import com.lorenzogao.jetpackexample.R
import com.lorenzogao.jetpackexample.dataStore
import kotlinx.android.synthetic.main.activity_data_store.*
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch


/**
 * Preferences DataStore 保留的位置是在 data/data/你的包名/files/datastore/自己设置名称_preferences.pd
 * 都是明文，所以刚开始就所说这个是不安全的
 *
 *
 *
 *
 *
 *
 */

class DataStoreActivity : AppCompatActivity() {



    val mainScope=   MainScope()
      val EXAMPLE_COUNTER by lazy {
          //DataStore 的key值  stringPreferencesKey 表示String  intPreferencesKey 表示 int ....
          stringPreferencesKey("example_counter") }


    val EXAMPLE_COUNTER1 by lazy {
        //DataStore 的key值  stringPreferencesKey 表示String  intPreferencesKey 表示 int ....
        intPreferencesKey("example_counter1") }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_data_store)

    }

    fun save(view: View) {
        if (etKey.text.isNullOrEmpty()) {
            return
        }
        if (etValue.text.isNullOrEmpty()) {
            return
        }
        if(rb_preferences.isChecked){
            mainScope.launch {
                dataStore.edit { settings ->
                    settings[EXAMPLE_COUNTER] = etValue.text.toString()
                    settings[EXAMPLE_COUNTER1] = 1

                }
            }
        }else{
            mainScope.launch {
                settingsDataStore.updateData { currentSettings ->
                    currentSettings.toBuilder()
                        .setExampleCounter(etValue.text.toString())
                        .build()
                }
            }
        }


    }



     fun query(view: View) {
        if (etKey.text.isNullOrEmpty()) {
            return

        }

         val exampleCounterFlow: Flow<String> =  if (rb_preferences.isChecked){
             dataStore.data.map { preferences ->
                     preferences[EXAMPLE_COUNTER] ?: "" }
         }else{

           settingsDataStore.data
                 .map { settings ->
                     // The exampleCounter property is generated from the proto schema.
                     settings.exampleCounter
                 }
         }
         mainScope.launch {
             exampleCounterFlow.collect {
                 tvContent.text = it
             }
         }
    }
}
